#!/bin/zsh

# Removing elements of Teamviewer, since they do not provide an unattened uninstaller!
# May impact other TV software if installed.

if [[ "$uninstall" != "true" ]]
then
	echo "Configured to not uninstall, leaving TV installed"
	exit 0
fi

current_uid=$(stat -f%u /dev/console)
current_user=$(id -un $current_uid)

# Launchd items should be unloaded first
function unload_launchd {

	lctl_label="$2"

	echo "Dolar 1: $1"
	echo "Dollar 2: $2"

	if [[ "$1" == "system" ]]
	then
		echo "Unload system: $lctl_label"

		launchctl bootout $1/$lctl_label 2>/dev/null
	else
		if [ $current_uid -ne 0 ]
		then

		echo "Unload user: $lctl_label"
		launchctl bootout gui/$current_uid/$lctl_label 2>/dev/null

		fi
	fi

}

while read line
do
	unload_launchd user "$line"

done < <(su -l $current_user -c "/bin/launchctl list" | awk '/com.teamviewer/ {print $NF}')

while read line
do
	unload_launchd system "$line"

done < <(launchctl list | awk '/com.teamviewer/ {print $NF}')

rm -Rf /Applications/TeamViewerHost.app
rm -Rf /Library/Audio/Plug-Ins/HAL/TVRemoteAudio.driver
rm -Rf /Library/Application\ Support/TeamViewer
rm -Rf /Library/Application\ Support/TeamViewer\ Host
rm -Rf /Library/Caches/com.teamviewer.TeamViewer*

rm /Library/PrivilegedHelperTools/com.teamviewer.Helper
rm /Library/Preferences/com.teamviewer.teamviewer.preferences.plist
rm /Library/LaunchDaemons/com.teamviewer*
rm /Library/LaunchAgents/com.teamviewer*

rm -Rf /Users/*/Library/Caches/com.teamviewer.TeamViewerHost 2>/dev/null
rm -Rf /Users/*/Library/Application\ Support/TeamViewer\ Host 2>/dev/null
rm -Rf /Users/*/Library/Caches/SentryCrash/TeamViewerHost 2>/dev/null

rm /Users/*/Library/Preferences/com.teamviewer.* 2>/dev/null

# Remove Teamviewer AuthPlugin
if [ $current_uid -eq 0 ]
then
	security authorizationdb read system.login.console > /tmp/teamviewer_authdb.xml

	db_counter=0
	while read line
	do
		if [[ "$line" =~ "TeamViewerAuthPlugin" ]]	
		then
			echo "$counter: Found TV Plugin"
			/usr/libexec/PlistBuddy -c "Delete mechanisms:$db_counter" /tmp/teamviewer_authdb.xml
		fi
	
		db_counter=$(( $counter + 1 ))

	done < <(/usr/libexec/PlistBuddy -c 'Print mechanisms' /tmp/teamviewer_authdb.xml)

	security authorizationdb write system.login.console < /tmp/teamviewer_authdb.xml
	
	rm -Rf /Library/Security/SecurityAgentPlugins/TeamViewerAuthPlugin.bundle
	
else
	echo "User logged in.  Security auth file left behind to prevent login window being killed."
fi
exit 0